<%-- 
    Document   : download
    Created on : Jul 3, 2013, 10:34:51 AM
    Author     : tuanta
--%>

<%@page import="java.util.ResourceBundle"%>
<%@page import="telsoft.file.util.FileUtil"%>
<%@page import="com.tg.smsgw.ws.AppServer"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="java.io.BufferedInputStream"%>
<%@page import="java.io.BufferedOutputStream"%>
<%@page import="com.tg.cms.entity.MDItem"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.File"%>
<%@page import="java.io.OutputStream"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
            ResourceBundle app = ResourceBundle.getBundle("app");
            String strKeyword = request.getParameter("key");
            String strRequestHeader = request.getHeader("user-agent");
            boolean accessFromAndroid = strRequestHeader.indexOf("Android") >=0;
            String strSubkeyName = accessFromAndroid?"android":"java";
            String strFileLocation = "/apps/media/sub";
            String strFileName = "";
            OutputStream os = null;
            InputStream is = null;
           try
            {
               strFileName = app.getString(strKeyword + "." + strSubkeyName);
               response.setContentType("application/octet-stream");
               response.setHeader("Content-Disposition", "attachment; filename=" + strFileName);
                os = new BufferedOutputStream(response.getOutputStream(),1024*128);
                String FILE_SEPARATOR = System.getProperty("file.separator");
                File downloadFile = new File(strFileLocation + FILE_SEPARATOR + strFileName);
                if(!downloadFile.exists())
                    throw new Exception("File not found:" + strFileLocation);
                is = new BufferedInputStream(new FileInputStream(downloadFile),1024*512);
                if (is == null) {
                    os.close();
                }
                else {
                    byte[] buffer = new byte[1024*128];
                    int len;

                    while ((len = is.read(buffer)) != -1) {    
                     os.write(buffer, 0, len);
                    }
                    os.flush();
                }
            }
//           catch (Exception e)
//            {
//               PrintWriter pw = respo                                                                                                                     nse.getWriter();
//               pw.println("<h1>" + e.getMessage() + "</h1>");
//               e.printStackTrace();
//            }
            finally{
                FileUtil.safeClose(is);
                FileUtil.safeClose(os);
            }
        %>
    </body>
</html>
